<template>
  <div class="alpha grid_3 omega">
    <div class="subject-info-title"><i class="fa fa-book"></i>专题与文章</div>
    <el-tree style="background: black; cursor: pointer" node-key="nodeId" ref="tree"  :data="nodeDatas" :props="defaultProps"
             lazy :load="loadDirNode" @node-click="handleNodeClick">
      <div class="subject-item" slot-scope="{ node, data }">
        <div class="subject-title"><a>{{node.label}}</a></div>
      </div>
    </el-tree>
  </div>
</template>

<script>
import { Tree } from 'element-ui'
import axios from '../../..//node_modules/axios/dist/axios'
export default {
  props: {
  },
  data () {
    return {
      nodeDatas: [],
      defaultProps: {
        children: 'children',
        label: 'label',
        isLeaf: 'isLeaf'
      }
    }
  },
  components: {
    elTree: Tree
  },
  methods: {
    recursionReplace (nodes, targetKey) {
      let findResult = {}
      if (this._.isEmpty(nodes)) {
        return findResult
      }

      for (let node of nodes) {
        if (node.nodeId === targetKey) {
          findResult = node
          break
        } else {
          findResult = this.recursionReplace(node.children, targetKey)
          // 回调结果判断是否找到
          if (!this._.isEmpty(findResult)) {
            break
          }
        }
      }
      return findResult
    },
    loadDirNode (node, resolve) {
      let _this = this
      axios.get('/article/loadSubject', {params: {nodeId: node.key}}).then(function (res) {
        if (res.data.status === 200) {
          let nodesArray = res.data.datas
          if (_this._.isEmpty(_this.nodeDatas)) { // 加载根节点
            _this.nodeDatas = nodesArray
          } else { //  加载子树节点
            let resultNode = _this.recursionReplace(_this.nodeDatas, node.key)
            if (!_this._.isEmpty(resultNode)) {
              _this.$set(resultNode, 'children', nodesArray)
              resolve(resultNode.children)
            }
          }
        }
      })
    },
    handleNodeClick (data, node, self) {
      if (node.isLeaf) {
        this.$router.push(`/specificArticle/${node.key}`)
      }
    }
  }
}
</script>
<style>
  /* 全局样式 */
.el-tree-node:focus>.el-tree-node__content {
  background-color: darkorange;
}
.el-tree-node__content:hover{
  background-color: darkorange;
}
.el-tree-node__expand-icon {
 color: rgba(255,255,255,1);
}
</style>
<style scoped>

.subject-title {
  font-size: 14px;
}
.subject-title a {
    display: block;
}
.subject-title a:hover {
  color: black;
}
.subject-item {
  color: rgba(255,255,255,1);
}
.subject-info-title {
  font-size: 16px;
  margin-left: 5px;
  margin-bottom: 10px;
}
</style>
